package jp.reflexworks.gae.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

public class Memcache {

	private Cache cache;

	public Memcache() throws CacheException {
		CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
		cache = cacheFactory.createCache(Collections.emptyMap());
	}

	public void put(Object key, Object value) {
		cache.put(key, value);
	}

	public Object get(Object key) {
		return cache.get(key);
	}

	public void remove(Object key) {
		cache.remove(key);
	}

	public boolean containsKey(Object key) {
		return cache.containsKey(key);
	}

	/**
	 * InputStreamからデータを読み、byte配列をMemcacheに保管する
	 * @param key key
	 * @param in InputStream
	 * @return InputStreamから取得したbyte配列
	 */
	public byte[] storedInMemcache(String key, InputStream in)
	throws IOException, CacheException {
		byte[] data = null;
		int dataPos = 0;
		byte[] temp = null;
		byte[] buffer = new byte[4096];
		int size;
		while ((size = in.read(buffer)) != -1) {
			if (dataPos > 0) {
				temp = new byte[dataPos];
				System.arraycopy(data, 0, temp, 0, dataPos);
				data = new byte[dataPos + size];
				System.arraycopy(temp, 0, data, 0, dataPos);
			} else {
				data = new byte[size];
			}
			System.arraycopy(buffer, 0, data, dataPos, size);
			dataPos = dataPos + size;
		}

		this.put(key, data);

		return data;
	}

}
